package com.huawei;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.DigestException;
import java.util.Date;

@WebServlet(name = "Cookie03",value = "/Cookie03")
public class Cookie03 extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");

        PrintWriter writer=resp.getWriter();

        Cookie[] cookies = req.getCookies();
        if(cookies!=null  && cookies.length>0){
            Boolean flag = false;
            for (Cookie cookie: cookies){
                String name = cookie.getName();
                int i =  1;
                if("count".equals(name)){
                    i = Integer.parseInt(cookie.getValue())+1;
                    Cookie cookie2 = new Cookie("count",Integer.toString(i));
                    cookie2.setMaxAge(60*60*24);
                    writer.println("欢迎回来，本次是第"+i+"次登录");
                    resp.addCookie(cookie2);
                }
                if("time".equals(name)){
                    flag = true;
                    String value = cookie.getValue();
                    writer.println("第"+i+"次登录时间"+value);
                    cookie.setValue(DateTest.getTime());
                    cookie.setMaxAge(60*60*24);
                    resp.addCookie(cookie);
                }


                }
            if(flag == false){
                Cookie cookie1 = new Cookie("time", DateTest.getTime());
                cookie1.setMaxAge(60*60*24);
                resp.addCookie(cookie1);

                Cookie cookie2 = new Cookie("count", "1");
                cookie1.setMaxAge(60*60*24);
                resp.addCookie(cookie2);

                writer.println("首次登录");
            }
        }
    }
}
